using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text.RegularExpressions;
using HQLAddin.Highlighting.Classificators.BaseClass;
using HQLAddin.Highlighting.Formatters;
using HqlIntellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;

namespace HQLAddin.Highlighting.Classificators
{
	[Export(typeof (IClassifierProvider))]
	[ContentType("xml")]
	internal sealed class KeywordClassifierProvider : IClassifierProvider
	{
		[Import] private IClassificationTypeRegistryService classificationRegistry;

		[Import]
		private Lazy<IConfigurationDataProvider> configurationDataProvider; //to speed up the first call.
		private IConfigurationDataProvider doNotDelete;

		#region IClassifierProvider Members

		public IClassifier GetClassifier(ITextBuffer textBuffer)
		{
			if(configurationDataProvider != null) doNotDelete = configurationDataProvider.Value;
			return textBuffer
				.Properties
				.GetOrCreateSingletonProperty(() => new KeywordClassifier(classificationRegistry));
		}

		#endregion
	}

	internal class KeywordClassifier : RegexBasedClassifier
	{
		private readonly string[] keywords = new[]
		                                     	{
		                                     		"join", "from", "select",
		                                     		"new", "where", "and",
		                                     		"or", "band", "between",
		                                     		"not", "join", "left",
		                                     		"inner", "fetch", "in",
		                                     		"group", "by", "sum", "count",
		                                     		"coalesce", "null", "is", "like", "having",
													"insert", "set", "delete", "update", "order"

		                                     	};

		public KeywordClassifier(IClassificationTypeRegistryService classificationRegistry)
			: base(classificationRegistry)
		{
		}

		public override string FormatterName
		{
			get { return KeywordFormat.Name; }
		}

		public override IEnumerable<Regex> Regexs
		{
			get
			{
				return from keyword in keywords
				       select new Regex(string.Format(@"\b({0})\b", keyword));
			}
		}
	}
}